package com.dolphin.plugin.handle;

import com.dolphin.model.Permission;
import com.dolphin.permission.MenuManager;
import com.dolphin.plugin.PluginInfo;
import com.dolphin.plugin.handle.base.BasePluginHandle;
import com.dolphin.service.PermissionService;
import org.springframework.context.ApplicationContext;

import java.util.List;

/**
 * @author dolphin
 * @description 插件权限注册
 * @date 2021/11/11 8:33
 */
public class PermissionHandle implements BasePluginHandle {

    ApplicationContext applicationContext;

    public PermissionHandle(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    @Override
    public void initialize() throws Exception {

    }

    @Override
    public void registry(PluginInfo plugin) throws Exception {
        PermissionService permissionService = applicationContext.getBean(PermissionService.class);
        List<Permission> permissionList = MenuManager.initSystemPermission(plugin.getClassList());
        permissionService.updatePermission(permissionList);
        MenuManager.PLUGIN_PERMISSION_MAPS.put(plugin.getPluginId(), permissionList);
    }

    @Override
    public void unRegistry(PluginInfo plugin) throws Exception {
        PermissionService permissionService = applicationContext.getBean(PermissionService.class);
        List<Permission> permissionList = MenuManager.PLUGIN_PERMISSION_MAPS.get(plugin.getPluginId());
        if (permissionList != null && permissionList.size() > 0) {
            permissionService.removePluginSystemPermissionList(permissionList);
            MenuManager.PLUGIN_PERMISSION_MAPS.remove(plugin.getPluginId());
        }
    }
}
